// 在全局定义API函数
import { wycUrl, drawUrl, apiMixUrlKeyApi } from '@/api/assemb.js'
// var andord = parseUrlParams(window.location.href)

export const apiMixin = {
  data() {
    return {
      show: false,
      writing: '',
      title: '',
      outline: '',
      creativeResult: null,
      creativeResults: '',
      compareResults: '',
      originality: '',
      aiLevel: 0,
      width: 0,
      arrIndex: [],
      widthIndex: 0,
      schedule: 0,
      text: '创作中,请稍后',
      scheduleShow: false,
      showDialog: false, // 对话框显示状态
    }
  },
  methods: {
    onDialogConfirm() {
      // 按钮被点击跳转至小程序客服页面
      jWeixin.miniProgram.navigateTo({ url: '/pages/service/service' })
    },
    onDialogCancel() {
      // 取消按钮被点击的操作 关闭dialog
      this.showDialog = false
    },
    change() {
      clearTimeout(this.time)
      clearTimeout(this.time1)
      clearTimeout(this.times)
      var settext = [
        '创作中,请稍后',
        '优化中,请稍后',
        '下载中,请稍后',
        '合并中,请稍后',
        '上传中,请稍后',
      ]
      let inx = 0
      this.widthIndex = 0
      this.schedule = 0
      this.arrIndex = this.arrIndex.map((item) => {
        return {
          ...item,
          width: 100 / this.arrIndex.length,
          widthChildren: 0,
        }
      })

      // 计算总进度
      let sum = () => {
        let number = this.arrIndex
          .map((item) => item.widthChildren)
          .reduce((accumulator, currentValue) => accumulator + currentValue)
        this.schedule = Math.floor(number / this.arrIndex.length)
      }
      const loadNextProgress = () => {
        if (this.widthIndex >= this.arrIndex.length) {
          this.time = setTimeout(() => {
            this.widthIndex = 0 // 重置为0，从新循环
            console.log('下一个进度条')
            loadNextProgress()
          }, 100) // 等待 1s 后重新开始加载
          if (this.widthIndex >= this.arrIndex.length - 1) {
            this.arrIndex.forEach((item) => {
              item.widthChildren = 0
            })
            inx += 1
            if (inx > 4) {
              this.text = settext[4]
            } else {
              this.text = settext[inx]
            }
            this.schedule = 0
            clearTimeout(this.time)
            this.time = null
          }
          this.time1 = setTimeout(() => {
            this.widthIndex = 0
            loadNextProgress()
            clearTimeout(this.time1)
          }, 300)
          return
        }
        if (this.widthIndex > 0) {
          // 如果是加载了第二个进度，则让上一个进度条伪 100%
          this.arrIndex[this.widthIndex - 1].widthChildren = 100
        }
        if (this.arrIndex[this.widthIndex].widthChildren < 99) {
          this.arrIndex[this.widthIndex].widthChildren++
          this.times = setTimeout(loadNextProgress, 300) // 间隔 100ms 执行下一次加载
        } else {
          this.widthIndex++ // 接着下一个进度跑
          loadNextProgress()
        }
        sum() // 计算整体的进度值
      }
      loadNextProgress()
    },
    async highCreate(param) {
    //   console.log('🚀 ~ file: original.js:109 ~ highCreate ~ param:', param)
      this.creativeResult = null
	  let title = this.writing.toString()
	  console.log(title,'这里显示的施恩')
      if (title.trim() == '') {
        uni.showToast({
          title: '请输入内容',
          duration: 2000,
          icon: 'none',
        })
      } else if (uni.getStorageSync('frequency') > 0 || this.isVip) {
        let str = title,
          arr = []
        traverse(str, 0)
        //   console.log(arr)
        // 进度条函数
        function traverse(x, z) {
          var m = x.substr(z, 200)
          var f = ['。', ',', '.', '?', ';', '!', '，', '？', '！', '；']
          var y = 200
          var ynum = []
          for (var j = 0; j < f.length; j++) {
            if (m.lastIndexOf(f[j]) > 0) {
              ynum.push(m.lastIndexOf(f[j]))
            }
          }
          if (ynum.length > 0) {
            y = Math.max.apply(null, ynum) + 1
          }
          arr.push(x.substr(z, y))
          z += y
          if (m.length >= 200) {
            return traverse(x, z)
          }
        }
        this.arrIndex = arr
        this.scheduleShow = true
        this.text = '创作中,请稍后'
        this.change()
        for (var i = 0; i < arr.length; i++) {}
        // 调用original函数获取结果
        // await this.original(param, i)
        await this.draw(param, i)
        // 显示结果
        if (this.creativeResult != null) {
          this.show = true
        }
        setTimeout(() => {
          this.scheduleShow = false
        }, 1000)

        uni.hideLoading()
      } else {
        this.isShowLoading = false
        uni.showToast({
          title: '可体验次数已用完,需开通会员才可使用',
          duration: 2000,
          icon: 'none',
        })
        // this.vipShow = true
      }
    },
    async draw(param) {
    //   console.log("🚀 ~ file: original.js:221 ~ draw ~ param:", param)
      await drawUrl(param, 1013, 'aiImage')
        .then((res) => {
          console.log("🚀 ~ file: original.js:225 ~ .then ~ res:", res)
          this.creativeResult = res.data.results
		  console.log(this.creativeResult,'这里打印的东西')
          // 函数的具体实现...
          setTimeout(() => {
            this.scheduleShow = false
          }, 1000)
          // 判断是否在微信小程序中打开页面
          // var andord = parseUrlParams(window.location.href)
          //   根据会员状态判断消耗次数
          if (res.data.code == 506) {
            this.scheduleShow = false
            this.showDialog = true
          }
          if (res.data.code == 404) {
            this.scheduleShow = false
            this.showDialog = true
          }
        //   this.creativeResult += res.data.data.results[0]
        //   show = true
          uni.hideLoading()
        })
        .catch((err) => {
            this.scheduleShow = false

          // 错误处理...
          //   console.log('失败了~~', i, err)
        })
    },
  },
}
